package com.myrent.config;

import com.myrent.shiro.CustomizedModularRealmAuthenticator;
import com.myrent.shiro.CustomizedModularRealmAuthorizer;
import com.myrent.shiro.EnterpriseRealm;
import com.myrent.shiro.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.authz.Authorizer;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
public class ShiroConfig {

    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setSuccessUrl("/index");
//        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //auonc:要认证才可以访问；anon：可以匿名访问
        filterChainDefinitionMap.put("/**/login", "anon");
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/**/register", "anon");
        filterChainDefinitionMap.put("/api/**", "anon");
        filterChainDefinitionMap.put("/**", "user");//登录可以访问
        filterChainDefinitionMap.put("/admin/**", "authc");
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/logout", "logout"); //配置退出

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }


    @Bean(name = "UserRealm")
    public UserRealm UserRealm() {
        UserRealm myUserRealm = new UserRealm();
        // 告诉realm,使用credentialsMatcher加密算法类来验证密文
        myUserRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myUserRealm;
    }

    @Bean(name = "EnterpriseRealm")
    public EnterpriseRealm EnterpriseRealm() {
        EnterpriseRealm enterpriseRealm = new EnterpriseRealm();
        // 告诉realm,使用credentialsMatcher加密算法类来验证密文
        enterpriseRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return enterpriseRealm;
    }

    /**
     * 配置安全管理器
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //添加2个realm。自己写的授权 验证
        securityManager.setAuthenticator(myRealmAuthenticator());
        securityManager.setAuthorizer(modularRealmAuthorizer());
        securityManager.setRealms(Arrays.asList(UserRealm(), EnterpriseRealm()));
        return securityManager;
    }


    /**
     * 自己重写的ModularRealmAuthorizer配置授权
     */
    @Bean
    public ModularRealmAuthorizer modularRealmAuthorizer() {
        CustomizedModularRealmAuthorizer authorizer = new CustomizedModularRealmAuthorizer();
        return authorizer;
    }

    /**
     *  自己重写的ModularRealmAuthenticator配置认证
     */
    @Bean
    public ModularRealmAuthenticator myRealmAuthenticator() {
        CustomizedModularRealmAuthenticator authenticator = new CustomizedModularRealmAuthenticator();
        authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
        return authenticator;
    }

    /**
     * 密码采用加密方式进行验证
     */
    @Bean(name = "hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(21);//散列的次数
        return hashedCredentialsMatcher;
    }

    /**
     * 开启shiro aop注解支持
     * (如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
     */
    @Bean(name = "authorizationAttributeSourceAdvisor")
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * Spring MVC的异常处理器
     */
    @Bean(name = "simpleMappingExceptionResolver")
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver() {
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
        mappings.setProperty("DatabaseException", "databaseError");
        mappings.setProperty("UnauthorizedException", "/user/403");
        resolver.setExceptionMappings(mappings);
        resolver.setDefaultErrorView("error");
        resolver.setExceptionAttribute("exception");
        return resolver;
    }

}
